package com.mirabelle.juice.service;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mirabelle.juice.service.AuthorService;
import com.mirabelle.juice.beans.UserDetailsImpl;
import com.mirabelle.juice.model.Author;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class UserDetailsServiceImpl implements UserDetailsService, Serializable {
	private static final long	serialVersionUID	= 1L;
	private transient Logger	log					= LoggerFactory.getLogger(getClass());
	
	@Autowired
	@Qualifier("AuthorService")
	protected AuthorService	authorService;
		
	@Override
	public UserDetails loadUserByUsername(String login)
			throws UsernameNotFoundException {
		log.info("Chargement initial des données de l'utilisateur pour le login : " + login);
		UserDetailsImpl loggedUser = new UserDetailsImpl();

		Author author = authorService.findAuthorByUniqueIdentifier(login);
		if (null == author) {
			log.error("identifiant '" + login + "' non trouvé dans la base de données");
			throw new UsernameNotFoundException("identifiant '" + login + "' non trouvé dans la base de données");
		}
		
		loggedUser.setUsername(author.getMail());
		loggedUser.setPassword(author.getPassword());
		loggedUser.addRole("ROLE_USER");

		log.debug("Recherche des preferences et des roles.");
		if (author.getAdmin()) {
			loggedUser.addRole("ROLE_ADMIN");
		}

		log.debug("Utilisateur authentifié construit : " + loggedUser);
		return loggedUser;
	}

}

